package com.yc.meeting_attendance.fragment;

import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.yc.meeting_attendance.MyApp;
import com.yc.meeting_attendance.R;
import com.yc.meeting_attendance.entity.UploadResutl;
import com.yc.meeting_attendance.net.AbsAPICallback;
import com.yc.meeting_attendance.net.Api;
import com.yc.meeting_attendance.utils.ApkUpdateManager;
import com.yc.meeting_attendance.utils.MyFileUtils;
import com.yc.meeting_attendance.utils.RestartAPPTool;
import com.yc.meeting_attendance.utils.SharePreferenceUtil;

import rx.Subscriber;

import static android.content.Context.INPUT_METHOD_SERVICE;

/**
 * Created by PC on 2017/4/13.
 */

public class SetDiagFragment extends DialogFragment implements View.OnClickListener {
    protected Subscriber subscriber;
    private TextView tvTitle;
    private View mainView;
    protected String mTitle;
    EditText et_pass,Modify_pass;
    Button btn_login,btn_save,btn_Update,btn_UpLoad;
    private FrameLayout cotainerView;
    protected Context mContext;
    public static Dialog progressDialog;
    LinearLayout ll2, ll1;
    EditText et_classNo, et_serverAddr,et_serverAddr1;
    SharePreferenceUtil mSharePreferenceUtil;
    private RadioGroup rg_com;
    RelativeLayout Update;
    int[] comIds = new int[]{R.id.rb_com0,R.id.rb_com1,R.id.rb_com2,
            R.id.rb_com3,R.id.rb_com4,R.id.rb_com5,
            R.id.rb_com6,R.id.rb_com7,R.id.rb_com8,
            R.id.rb_com9};
    TextView versions;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public void onStart() {
        super.onStart();
        getDialog().getWindow().setLayout(1150, 860);//设置对话框宽高
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mainView = inflater.inflate(R.layout.activity_set, container);
        mSharePreferenceUtil = MyApp.getsInstance().sharePreferenceUtil;

        btn_Update = (Button) mainView.findViewById(R.id.btn_Update);
        btn_Update.setOnClickListener(this);
        btn_UpLoad = (Button) mainView.findViewById(R.id.btn_UpLoad);
        btn_UpLoad .setOnClickListener(this);

        TextView tvClose = (TextView) mainView.findViewById(R.id.tv_close);
        et_pass = (EditText) mainView.findViewById(R.id.et_pass);
        btn_login = (Button) mainView.findViewById(R.id.btn_login);
        ll1 = (LinearLayout) mainView.findViewById(R.id.ll1);
        ll2 = (LinearLayout) mainView.findViewById(R.id.ll2);
        et_classNo = (EditText) mainView.findViewById(R.id.et_classNo);
        btn_save=(Button)mainView.findViewById(R.id.btn_save);
        et_serverAddr = (EditText) mainView.findViewById(R.id.et_serverAddr);
        btn_save.setOnClickListener(this);
        et_serverAddr1 = (EditText) mainView.findViewById(R.id.et_serverAddr1);
        rg_com = (RadioGroup)mainView.findViewById(R.id.rg_com);
        Update=(RelativeLayout)mainView.findViewById(R.id.Update);
        Update.setOnClickListener(this);
        Modify_pass=(EditText)mainView.findViewById(R.id.Modify_pass);
        rg_com.check(comIds[mSharePreferenceUtil.getCom()]);
        et_classNo.setText(mSharePreferenceUtil.getEquipment());
        et_serverAddr.setText(mSharePreferenceUtil.getCampusServerAddress());
        versions = (TextView) mainView.findViewById(R.id.versions);
        et_serverAddr1.setText(mSharePreferenceUtil.getServerAddress());
        btn_login.setOnClickListener(this);
        tvClose.setOnClickListener(this);
        try {
            versions.setText("当前版本号为："+getVersionName(getActivity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mainView;
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                if (et_pass.getText().toString().equals("666666")) {
                    ll1.setVisibility(View.GONE);
                    ll2.setVisibility(View.VISIBLE);
                    btn_login.setVisibility(View.GONE);
                    InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(INPUT_METHOD_SERVICE);
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                } else {
                    Toast.makeText(getActivity(), "密码错误，请重新输入", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.tv_close:
                dismiss();
                break;
            case R.id.btn_save:
                mSharePreferenceUtil. setEquipment(et_classNo.getText().toString());
                mSharePreferenceUtil.setCampusServerAddress(et_serverAddr.getText().toString());
                mSharePreferenceUtil.setServerAddress(et_serverAddr1.getText().toString());
                RadioButton rb = (RadioButton) mainView.findViewById(rg_com.getCheckedRadioButtonId());
                String com = rb.getText().toString().replace("com","");
                mSharePreferenceUtil.setCom(Integer.valueOf(com));
                mSharePreferenceUtil.setPass(Modify_pass.getText().toString());
                doClearDataReStart();
                //重启
                RestartAPPTool.restartAPP(getActivity());
                break;
            case  R.id.Update://升级APP

                getAppInfo();
                break;
            case R.id.btn_Update: //更新课程信息
                //更新课程信息
                doClearDataReStart();
                //重启
                RestartAPPTool.restartAPP(getActivity());

                break;
            case R.id.btn_UpLoad://上传课程记录
                mSharePreferenceUtil.setIsManualUpload(true);
                SetDiagFragment.this.dismiss();
                break;
        }
    }

    /**
     * 清除缓存
     */
    private void doClearDataReStart() {
        //
        mSharePreferenceUtil.setRestartFlag("");
        mSharePreferenceUtil.setRealized(0);
        mSharePreferenceUtil.setIndexEnd(0);
        mSharePreferenceUtil.setIndexBigen(0);
        mSharePreferenceUtil.setSubscript(false);
        mSharePreferenceUtil.setFig(false);
        mSharePreferenceUtil.setDataFig(false);
        mSharePreferenceUtil.setIsFlagTui(false);
        mSharePreferenceUtil.setIsManualUpload(false);


    }

    int Version=0;
    private void getAppInfo() {
        Subscriber<UploadResutl> subscriber = new AbsAPICallback<UploadResutl>(mContext) {
            @Override
            public void onNext(UploadResutl versionsResult) {
                Version = Integer.parseInt(versionsResult.getVersion());
                Log.d("TAG","Version:"+Version);
                try {
                    if ((getVersionCode(getActivity()))<Version){
                        //这里来检测版本是否需要更新
                        ApkUpdateManager apkUpdateManager = new ApkUpdateManager(getActivity(), versionsResult.getUrl());
                        apkUpdateManager.checkUpdateInfo();

                    }else {
                        Toast.makeText(getActivity(),"此版本为最新版本,版本号为"+getVersionName(getActivity()),Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);

            }
        };

        Api.getInstance().UploadApk(subscriber);
    }
    /*
 * 获取当前程序的版本号
 */
    public    int getVersionCode(Context context) throws Exception{
        //获取packagemanager的实例
        PackageManager packageManager = context.getPackageManager();
        //getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
        return  packInfo.versionCode;
    }
    /*
     * 获取当前程序的版本号
     */
    public    String getVersionName(Context context) throws Exception{
        //获取packagemanager的实例
        PackageManager packageManager = context.getPackageManager();
        //getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
        return  packInfo.versionName;
    }
}
